package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.RoleMapper;
import com.itheima.health.dao.RoleMenuMapper;
import com.itheima.health.dao.RolePermissionMapper;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.RoleMenu;
import com.itheima.health.pojo.RolePermission;
import com.itheima.health.service.RoleService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@DubboService
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        if (queryPageBean.getQueryString() != null) {
            criteria.orLike("name", "%" + queryPageBean.getQueryString() + "%");
            criteria.orLike("keyword", "%" + queryPageBean.getQueryString() + "%");
        }
        Page<Role> page = (Page<Role>) roleMapper.selectByExample(example);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void add(Role role) {
        int i = roleMapper.insertSelective(role);
    }

    @Override
    public Role findByName(String name) {
        Role findbyrolename = roleMapper.findbyrolename(name);
        return findbyrolename;
    }

    @Override
    public Role findById(Integer id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public void edit(Role role) {
        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public void delete(Integer id) {
        Role role = new Role();
        role.setId(id);
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(role.getId());
        rolePermissionMapper.delete(rolePermission);
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(role.getId());
        roleMenuMapper.delete(roleMenu);
        roleMapper.delete(role);
    }
}
